let path = require('path')
let fs = require('fs')

let mime = require('mime-types')

let promisify = require('util').promisify

let readFile = promisify(fs.readFile)
let readdir = promisify(fs.readdir)
let writeFile = promisify(fs.writeFile)

let targetPath = path.join(__dirname, 'icons')

/**
 * creat icon css style
 */
async function main() {
  let imageFileList = await readdir(targetPath)

  let promiseList = imageFileList.filter(file => !file.startsWith('.')).map(file => {
    let basename = path.basename(file, path.extname(file)).replace(/[.|/]/g, '-')
    return readImageToBase64(path.join(targetPath, file), basename)
  })

  let dataList = await Promise.all(promiseList)
  
  await saveToFile(dataList.map(createCssRule).join('\n\n'))
}

function createCssRule(data = {}) {
  let { imageBase64, basename } = data
  return `#files .icon-${basename} .name { background-image: url(${imageBase64}) }`
}

async function readImageToBase64(filename, basename) {
  let data = await readFile(filename)
  let contentType = mime.lookup(filename)
  let base64 = new Buffer(data, 'binary').toString('base64')
  let imageBase64 = `data:${contentType};base64,` + base64
  return { imageBase64, basename }
}

main()

async function saveToFile(content, filename) {
  if (!filename) {
    filename = 'icon.css'
  }
  filename = path.join(__dirname, filename)

  await writeFile(filename, content, 'utf8')
  console.log('更新 css 成功')
}


